package dk.com.entities;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import dk.com.util.ClassUtils;

public class SQLHelper<T extends BaseEntities> {

	private Class<T> clazz;

	public SQLHelper(Class<T> theClass) {
		this.clazz = theClass;
	}

	public String makeSQLCreateTableFromEntities(){
		
		
		String sql = ""; 
		sql = "CREATE TABLE " + clazz.getSimpleName() + "(";
		
		List<Field> fields = ClassUtils.getAllFields(clazz);
		for (Field field : fields) {
			String type = convertToSQLType(field.getGenericType().toString());
			if (!type.isEmpty()) {
				if (field.getName().equalsIgnoreCase("pKey")) {
					sql += field.getName() + " " + type + " PRIMARY KEY,"; 
				} else {
					sql += field.getName() + " " + type + ",";
				}
			}
		}
		if (sql.endsWith(",")) {
			sql = sql.substring(0, sql.length()-1);
		}
		
		sql+=")";
		
		return sql;
	}

	private String convertToSQLType(String javaType) {
		String sqlType = "";
		if (javaType.equalsIgnoreCase(String.class.toString())) {
			sqlType = "VARCHAR";
		}

		if (javaType.equalsIgnoreCase(Boolean.class.toString())) {
			sqlType = "BIT";
		}

		if (javaType.equalsIgnoreCase(Byte.class.toString())) {
			sqlType = "TINYINT";
		}

		if (javaType.equalsIgnoreCase(Short.class.toString())) {
			sqlType = "SMALLINT";
		}

		if (javaType.equalsIgnoreCase(Integer.class.toString())) {
			sqlType = "INTEGER";
		}

		if (javaType.equalsIgnoreCase(Long.class.toString())) {
			sqlType = "BIGINT";
		}

		if (javaType.equalsIgnoreCase(Double.class.toString())) {
			sqlType = "FLOAT";
		}

		if (javaType.equalsIgnoreCase(Byte[].class.toString())) {
			sqlType = "BINARY";
		}

		if (javaType.equalsIgnoreCase(Date.class.toString())) {
			sqlType = "DATE";
		}

		if (javaType.equalsIgnoreCase(Timestamp.class.toString())) {
			sqlType = "TIMESTAMP";
		}
		return sqlType;
	}

	public String makeSQLGetAll(){
		String sql = ""; 
		sql = "SELECT * FROM " + clazz.getSimpleName();
		return sql;
	}
}
